<template>
	<echelon-solutions>
		<!-- 这里是顶部导航栏 -->
		<skyline-navigation title="结算账单"></skyline-navigation>
		<!-- 这里是中间区域 -->
		<central-hub>
			<view class="container flexGap flex-column">
				<view class="flexGap Aitems-center">
					<button :type="statusFlag?'warn':'primary'"
						@click="statusFlag=!statusFlag">{{statusFlag?'切换未结算':'切换结算'}} </button>

					<button @click="visible = true;" class="w30" v-if="has('/bill/details/recordBillCreate')"
						:disabled="statusFlag">结算</button>
				</view>
				<view class="flexGap Aitems-center">
					<my-select v-model="datesCr" :options="MonthList" multiple v-if="!statusFlag"></my-select>
					<my-select v-model="datesEx" :options="MonthListEx" multiple v-else></my-select>
					<button @click="handleSearch()" class="w30">搜索</button>
				</view>
				<view v-for="(v,i) of dataList " :key="i" v-if="dataList.length">
					<view v-if="!v.total">
						<view class="title" style="zoom: .5;">
							<view>{{v.title}}</view>
						</view>
						<MyTable :columns="v.header ||columnsData" :dataSource="v.displayedItems" style="zoom: .8;">
						</MyTable>

					</view>
				</view>
				<MyPopup v-model="visible">
					<view>
						<view class="flexGap flex-column">
							<button type="primary" @click="submit()">结算</button>
							<MyTreeTable style="height: 60vh;overflow: scroll;zoom: .8;" :columns="columns"
								:dataSource="allAccountInfo" selectable v-model="selectedRows">
							</MyTreeTable>

						</view>
					</view>
				</MyPopup>
			</view>
		</central-hub>
	</echelon-solutions>
</template>

<script>
	export default {
		methods: {
			// 当前账单是否结算
			submit() {
				if (this.selectedRows.length === 0) {
					uni.showToast({
						title: '你没有选中结算账号',
						icon: 'error',
						duration: 2000
					});
					return false;
				}
				uni.showModal({
					title: '是否结算',
					success: (res) => {
						if (res.confirm) {
							this.$postPublic(['detail', 'recordBillCreate', 'post'], {
								dates: JSON.stringify(this.datesCr),
								ids: JSON.stringify(this.selectedRows),
							}, () => {
								setTimeout(() => {
									uni.showToast({
										title: '结算成功...',
										icon: 'none'
									});
								}, 100);
								this.readLoad();
							});
						}
					}
				})
			},



			parseDateRange(dateRange) {
				const [startDate, endDate] = dateRange.split('至');
				const start = new Date(startDate);
				const end = new Date(endDate);

				const result = [];
				let current = new Date(start);

				while (current <= end) {
					const year = current.getFullYear();
					const month = current.getMonth() + 1; // 月份从0开始，因此要加1
					result.push(`${year}/${month}`); // 补零操作

					// 增加一个月
					current.setMonth(current.getMonth() + 1);
				}

				return result;
			},
			calculatePercentage(val, input) {
				if (typeof input === 'number' && input <= 1) {
					return val * input;
				} else if (typeof input === 'string' || input.endsWith('%')) {
					const numberInput = parseFloat(input);
					if (!isNaN(numberInput)) {
						return val * (numberInput / 100);
					}
				}

				return null; // 输入格式无效时返回null或其他适当的值
			},
			/**
			 * 处理搜索操作
			 * @param {boolean} flag - 是否进行搜索操作的标志
			 * @param {string} [val=''] - 日期范围，默认为空字符串
			 */
			async handleSearch() {
				const createDate = this.findMinMaxDate();
				if (!createDate) {
					uni.showToast({
						title: '请选择时间',
						icon: 'none'
					});
					return false;
				}
				const dates = this.statusFlag ? this.datesEx : this.datesCr;
				this.$storage.set('deDate', [dates, this.statusFlag]);
				const info = this.info;
				this.dataList = [];
				const parsedDates = this.parseDateRange(createDate);
				// 调用接口请求数据并处理返回结果
				const {
					data,
				} = await this.$listPublic('detail', {
					...info,
					createDate
				});
				const len = data.length;
				let t = 0,
					y = 0,
					u = 0;
				for (let i = 1; i < len; i++) {
					const {
						name,
						title,
						displayedItems
					} = data[i];
					const ary = [];
					parsedDates.forEach(date => {
						const a = displayedItems.filter(it => {
							const [y, m] = it.createDate.split('/');
							return date === (y + '/' + m)
						});
						const outfit = a
							.filter(it => it.remarks.includes('新装'))
							.map(it => parseFloat(it.amountReceived))
							.reduce((acc, curr) => acc + curr, 0).toFixed(2);
						const renewal_fee = a.filter(it => it.remarks.includes('续费')).map(it => parseFloat(it
								.amountReceived))
							.reduce((acc, curr) => acc + curr, 0).toFixed(2);

						ary.push({
							date,
							outfit,
							renewal_fee,
							total: (parseFloat(outfit) + parseFloat(renewal_fee)).toFixed(
								2)
						})
					});
					const tal = ary.map(it => parseFloat(it.total))
						.reduce((acc, curr) => acc + curr, 0).toFixed(2);
					const total = {
						date: '总收费100%',
						outfit: '网管预结' + this.calculatePercentage(100, info.preSettlementRate) + '%',
						renewal_fee: '公寓剩余' + this.calculatePercentage(100, info.neIncomeRate) + '%',
						total: ''
					}
					const total2 = {
						date: tal,
						outfit: this.calculatePercentage(tal, info.preSettlementRate).toFixed(2),
						renewal_fee: this.calculatePercentage(tal, info.neIncomeRate).toFixed(2),
						total: ''
					}
					t += parseFloat(tal);
					y += parseFloat(total2.outfit);
					u += parseFloat(total2.renewal_fee);
					this.dataList.push({
						title,
						displayedItems: [...ary, {
							date: '',
							outfit: '',
							renewal_fee: '',
							total: tal
						}, total, total2],
						is: i === 1
					});
					if (i === len - 1) {
						const columns = [
							'日期,date',
							'总收入,total',
							'网管预结,outfit', '公寓剩余,renewal_fee',
						];
						this.dataList.unshift({
							title: createDate + '季度总结',
							header: this.myColumns(columns),
							displayedItems: [{
								date: createDate,
								outfit: y.toFixed(2),
								renewal_fee: u.toFixed(2),
								total: t.toFixed(2)
							}],
							is: i === 1
						});
					}

				}
			},
			generateFormFields(fields) {
				return fields.filter(field => field);
			},
			// 生成表格头
			myColumns(columnData) {
				return columnData.map(data => {
					const [title, key, fixed] = data.split(',');
					const column = {
						title,
						key
					};
					if (fixed) {
						column.fixed = fixed;
					}
					return column;
				});
			},
			findMinMaxDate() {
				const dates = this.statusFlag ? this.datesEx : this.datesCr;
				if (!Array.isArray(dates)) {
					return "";
				}

				if (dates.length === 0) {
					return "";
				}

				var minDate = dates[0];
				var maxDate = dates[0];

				for (var i = 1; i < dates.length; i++) {
					if (dates[i] < minDate) {
						minDate = dates[i];
					}

					if (dates[i] > maxDate) {
						maxDate = dates[i];
					}
				}
				const {
					startDate
				} = this.generateMonth.find(it => it.value === minDate);
				const {
					endDate
				} = this.generateMonth.find(it => it.value === maxDate);
				return (startDate && endDate) ? startDate + '至' + endDate : false;
			},
			generateMonthList() {
				var startDate = new Date('2023-11-01');
				var currentDate = new Date();
				var monthList = [];

				while (startDate <= currentDate) {
					var year = startDate.getFullYear();
					var month = ('0' + (startDate.getMonth() + 1)).slice(-2);
					var lastDay = new Date(year, startDate.getMonth() + 1, 0).getDate(); // 获取当月最后一天
					monthList.push({
						label: `${year}-${month}`,
						value: `${year}-${month}`,
						startDate: `${year}-${month}-01`,
						endDate: `${year}-${month}-${lastDay}`
					});

					startDate.setMonth(startDate.getMonth() + 1);
				}

				return monthList;
			},
			async readLoad() {
				const {
					data
				} = await this.$postPublic(['detail', 'recordBill']);
				// 使用示例
				const d = data.map(it => it.date);
				this.generateMonth = this.generateMonthList();
				this.MonthList = this.generateMonth.filter(it => !d.includes(it.value));
				this.MonthListEx = this.generateMonth.filter(it => d.includes(it.value));
				this.datesCr = [];
				this.datesEx = [];
				this.dataList = [];
				this.visible = false;
			}

		},
		onLoad(options) {
			this.info = options.data ? JSON.parse(options.data) : this.$storage.get('login');
			this.readLoad();
			const columns = [
				'日期,date',
				'新装,outfit', '续费,renewal_fee',
				'合计,total'
			];
			(async () => {
				this.columnsData = this.myColumns(columns); // 生成表头
				// 调用接口请求数据并处理返回结果
				const allAccountInfo = await this.$listPublic('account', this.info);
				this.allAccountInfo = [allAccountInfo];
				const [date, flag] = this.$storage.get('deDate') || [];
				this.statusFlag = flag; 
				if (date) {
					if (this.statusFlag) {
						this.datesEx = date;
					} else {
						this.datesCr = date;
					}
					this.handleSearch();
				}
			})()

		},
		data() {
			return {
				info: null,
				generateMonth: [],
				statusFlag: false,
				datesCr: [],
				datesEx: [],
				MonthList: [],
				MonthListEx: [],
				columnsData: [],
				columns: [{
						title: 'ID',
						key: 'id'
					},
					{
						title: '账号',
						key: 'username'
					},
					{
						title: '用户名',
						key: 'name'
					},
				],
				dataSource: [],
				selectedRows: [],
				visible: false,
				selectedOptions: [],
				allAccountInfo: [],
				updateDateList: [], // 更新季度数组
				dateSelect_options: [], //季度列表 
				dataList: [], // 表格数据 
			}
		},

	}
</script>

<style scoped>
	.container {
		padding: 10rpx;
		background-color: #fff;
		box-sizing: border-box;
	}

	.gap_img {
		border-radius: 4px;
	}

	.title {
		font-weight: bold;
		color: #000;
		border: solid 1px gainsboro;
		padding: 8px;
		box-sizing: border-box;
		border-bottom: none;
		border-top-left-radius: 4px;
		border-top-right-radius: 4px;
		box-shadow: 0 -1px 0 gainsboro;
		text-align: center;
		background: #db9b6d;
		font-size: 30px;
	}

	.w100 {
		width: 100%;
	}

	.w30 {
		width: 30%;
	}

	.zoom3 {
		zoom: .3
	}

	.is_p {
		padding-top: 10px;
		border-top: red solid 10px;
	}
</style>